<template>
  <el-dialog class="xiaobu-form-dialog" v-bind="$attrs" v-on="$listeners">
    <div class="el-dialog-body-child">
      <el-form
        ref="dialogFormRef"
        class="clearfix"
        :model="dialogForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item class="all" label="用户名" prop="userName">
          <el-input
            v-model.trim="dialogForm.userName"
            clearable
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item class="all" label="性别" prop="sex">
          <el-select-dict
            dictType="SEX"
            v-model="dialogForm.sex"
            clearable
            placeholder="请选择性别"
          />
        </el-form-item>
        <el-form-item class="all" label="邮箱" prop="email">
          <el-input
            v-model.trim="dialogForm.email"
            clearable
            placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item v-if="userInfo.email !== dialogForm.email" class="all" label="邮箱验证码" prop="emailCode">
          <vue-message-code class="get-code" beginMsg="获取邮箱验证码" :getCodeApi="getCodeApi" :validateForm="validateForm"></vue-message-code>
          <el-input :maxlength="6" v-model.trim="dialogForm.emailCode" placeholder="请输入邮箱验证码" />
        </el-form-item>
        <el-form-item class="all" label="头像" prop="avatarList">
          <xiaobu-upload-img :openCropper="true" @imgChange="handleImgChange" :max="1" :imgList="dialogForm.avatarList"></xiaobu-upload-img>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <template>
        <el-button @click="$emit('close')">关 闭</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </template>
    </div>
  </el-dialog>
</template>
<script>
import XiaobuUploadImg from "@/components/upload-img/index.vue"
import {commonApi} from "@/api"
import { emailReg } from "@/utils/check-reg.js"
export default {
  name: "EditUserInfo",
  components: {
    XiaobuUploadImg
  },
  data() {
    return {
      dialogForm: {
        userName: "",
        sex: "",
        email: "",
        emailCode: "",
        avatar: "",
        avatarList: [],
        deleteFiles: "" // 要删除的图片列表
      },
      rules: {
        userName: [{required: true, message: "请输入用户名", trigger: ["blur"]}],
        sex: [{required: true, message: "请选择性别", trigger: "change"}],
        email: [
          { required: true, message: "请输入邮箱", trigger: ["blur"] },
          { pattern: emailReg, message: "请输入正确的邮箱", trigger: ["blur"] }
        ],
        emailCode: [{required: true, message: "请输入邮箱验证码", trigger: "blur"}],
        avatarList: [{required: true, message: "请上传头像", trigger: "change"}]
      }
    }
  },
  methods: {
    // 重置表单
    resetDialogForm() {
      this.dialogForm = {
        userName: this.userInfo.userName,
        sex: this.userInfo.sex,
        email: this.userInfo.email,
        emailCode: "",
        avatar: this.userInfo.avatar,
        avatarList: [{
          name: "头像",
          url: this.userInfo.avatar
        }],
        deleteFiles: ""
      }
      this.$nextTick(() => {
        this.$refs.dialogFormRef&&this.$refs.dialogFormRef.clearValidate()
      })
    },
    //校验邮箱
    validateForm() {
      return new Promise(resolve => {
        this.$refs.dialogFormRef.validateField("email", errMsg => {
          if (!errMsg) {
            resolve({ result: true, msg: "校验通过" })
          } else {
            resolve({ result: false, msg: errMsg })
          }
        })
      })
    },
    // 校验通过 获取邮箱验证码
    getCodeApi() {
      commonApi.sendEmail({email: this.dialogForm.email}).then(data => {
        this.$modal.msgSuccess(data.msg)
      })
    },
    // 图片改变事件
    handleImgChange(avatarList) {
      this.dialogForm.avatarList = avatarList
      this.$refs.dialogFormRef.validateField("avatarList")
    },
    // 保存个人信息
    save() {
      this.$refs.dialogFormRef.validate(async valid => {
        if (valid) {
          const formData = new FormData()
          const targetItem = this.dialogForm.avatarList[0] 
          if (targetItem.raw) {
            formData.append("file", targetItem.raw, targetItem.name)
            const data = await commonApi.upload(formData)
            if (!data) { return }
            this.dialogForm.deleteFiles = this.dialogForm.avatar
            this.dialogForm.avatar = data.url
          }
          const params = JSON.parse(JSON.stringify(this.dialogForm))
          delete params.avatarList
          commonApi.editUserInfo(params).then(data => {
            const userInfo = Object.assign(this.userInfo, this.dialogForm)
            this.$store.commit("user/SET_USER_INFO", userInfo)
            this.$emit("close")
            this.$modal.msgSuccess(data.msg)
          })
        }
      })
    }
  }
}
</script>
